<?php

class ShopController extends BaseController {
    
    public function indexAction () {
        $model_shop = new ShopModel();
        
        $this->shops = $model_shop->getRecent10Shops();
        return 'shop/index';
    }
    
    public function addAction () {
        if (! $_POST) {
            $model_station = new StationModel();
            $model_tag = new TagModel();
            $stations = $model_station->getStations();
            foreach ($stations as $v){
                $station_list[$v->line . '号线:' .$v->name] = $v->id; 
            }
            $tags = $model_tag->getTags();
            foreach ($tags as $tag){
                $array[$tag->id] = $tag->name;
            }
            $this->tags = $array;
            $this->station_list = $station_list;
            return 'shop/add';
        } else {

            $form = $this->_buildForm();
            $form->setValue($_POST);
            $value = $form->getValue();
            $value['create_time'] = time();
            
            $model_shop = new ShopModel();
            $shop_id = $model_shop->addShop($value);
            
            $model_shoptag = new ShopTagModel();
            foreach ($_POST['tag'] as $v){
                $model_shoptag->insert(array('shop_id'=>$shop_id, 'tag_id'=>$v));
            }

            
            if($shop_id){
                $this->redirect('notify/success');
            }else{
                $this->redirect('notify/error');
            }
        }
    }
    
    /**
     * @return Form
     */
    private function _buildForm () {
        $form = new Form('shop', array(
            'method' => 'post' , 
            'action' => $this->makeUri('shop/add') , 
            'enctype' => 'multipart/form-data'));
        
        $input = new Form_Input('name', array(
            'type' => 'text' , 
            'label' => '店名'));
        $filter = new Filter();
        $filter->addFilter(new Filter_LowerCase());
        $input->addFilter($filter);
        
        $form->addElement($input);
        
        $form->addElement(new Form_Textarea('intro', array(
            'label' => '介绍')));
        
        $form->addElement(new Form_Input('address', array(
            'type' => 'text' , 
            'label' => '地址')));
        
        $form->addElement(new Form_Input('owner', array(
            'type' => 'text' , 
            'label' => '店主')));
        
        $form->addElement(new Form_Input('station_id', array(
            'type' => 'text' , 
            'label' => '站点')));
        
        $form->addElement(new Form_Input('gate', array(
            'type' => 'text' , 
            'label' => '出口')));

        return $form;
    }
}
?>